package com.xr.sy.modules.message.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.Producer;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.xr.common.service.impl.CrudServiceImpl;
import com.xr.sy.modules.message.dao.SysMailDao;
import com.xr.sy.modules.message.dto.SysMailDTO;
import com.xr.sy.modules.message.email.EmailUtils;
import com.xr.sy.modules.message.entity.SysMailEntity;
import com.xr.sy.modules.message.service.SysMailService;
import com.xr.sy.modules.security.service.CaptchaService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 邮箱
 *
 * @author Joe 825525632@qq.com
 * @since 1.0.0 2019-11-26
 */
@Service
public class SysMailServiceImpl extends CrudServiceImpl<SysMailDao, SysMailEntity, SysMailDTO> implements SysMailService {

    @Autowired
    private CaptchaService captchaService;

    @Lazy
    @Autowired
    private EmailUtils emailUtils;

    @Override
    public QueryWrapper<SysMailEntity> getWrapper(Map<String, Object> params) {
        String email = (String) params.get("email");

        QueryWrapper<SysMailEntity> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(email), "email", email);

        return wrapper;
    }

    @Override
    public SysMailEntity getByMail(String email){
        QueryWrapper<SysMailEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("email", email);
        List<SysMailEntity> list = baseDao.selectList(wrapper);
        if(CollectionUtils.isNotEmpty(list)){
            return list.get(0);
        }else {
            return  null;
        }

    }


    @Override
    public boolean sendVerifyCode(String email) throws Exception {
        String[] to = new String[]{email};
        SysMailEntity sysMailEntity =  getByMail(email);
        if(null != sysMailEntity){
            //生成文字验证码
            String code = captchaService.createCode(email);
            return emailUtils.sendMail(to, null, "验证码", code);
        }else {
            return false;
        }
    }


}